package com.lzy.cloud.search.client.service.impl;

import com.lzy.cloud.search.client.entity.EsIndex;
import com.lzy.cloud.search.client.entity.EsQuery;
import com.lzy.cloud.search.client.service.DeleteDocumentService;
import com.lzy.cloud.search.client.util.EsClient;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 删除文档
 */
@Service
public class DeleteDocumentServiceImpl implements DeleteDocumentService {

    @Autowired
    private EsClient client;


    @Override
    public Boolean forDelete(EsIndex esIndex)   {
        DeleteResponse response = client.getConnection().prepareDelete(esIndex.getName(), esIndex.getType(), esIndex.getId()).get();
        System.out.println("删除成功！");
        return response!=null;
    }

    /**
     * 根据查询条件删除
     *
     * @ 
     */
    @Override
    public void forDeleteByQuery(EsQuery esQuery)   {
        DeleteByQueryAction.INSTANCE.newRequestBuilder(client.getConnection()).filter(QueryBuilders.termQuery(esQuery.getFieldName(), esQuery.getFieldText())).execute().actionGet();

        System.out.println("删除成功！");
    }


    /**
     * 如果删除的比较多，需要执行的时间比较长，建议使用异步的删除操作
     */
    @Override
    public void forAsyncDeleteByQuery(EsQuery esQuery)   {


        DeleteByQueryAction.INSTANCE.newRequestBuilder(client.getConnection())
                .filter(QueryBuilders.matchQuery(esQuery.getFieldName(), esQuery.getFieldText()))
                .source(esQuery.getIndices())
                .execute(new ActionListener<BulkByScrollResponse>() {
                    @Override
                    public void onResponse(BulkByScrollResponse response) {
                        long deleted = response.getDeleted();
                        System.out.println("异步删除成功！" + deleted);
                    }

                    @Override
                    public void onFailure(Exception e) {
                        // Handle the exception
                        System.out.println("异步删除失败:" + e.getMessage());
                    }
                });
    }

}
